﻿namespace EyeOpen.DataEntry.Web.Mvc
{
	using System;
	using System.Linq;
	using System.Web;
	using System.Web.Mvc;
	using AutoMapper;
	using EyeOpen.DataEntry.Data;
	using EyeOpen.DataEntry.Domain;
	using EyeOpen.Web.Mvc;
	using EyeOpen.Web.Mvc.Models;

	public class CustomerController : BaseController
	{
		private readonly IShopUnitOfWork unitOfWork;

		public CustomerController(IShopUnitOfWork unitOfWork)
		{
			this.unitOfWork = unitOfWork;

			Initialize();
		}
				
		[HttpGet]
		public ActionResult List()
		{
			using (unitOfWork)
			{
				var customerList =
					unitOfWork
						.CustomerRepository
						.ToList()
						.Select(Mapper.Map<Customer, CustomerModel>);
			
				return Render("List", new CustomerListModel(customerList));
			}
		}

		[HttpPost]
		public ActionResult Create()
		{
			return Render("Create", new CustomerModel());
		}

		[HttpPost]
		public ActionResult Add(CustomerModel customerModel)
		{
			if (!ModelState.IsValid)
			{
				return Render("Create", customerModel);
			}

			using (unitOfWork)
			{
				var customer = Mapper.Map<CustomerModel, Customer>(customerModel);

				customer.Id = Guid.NewGuid();
				unitOfWork.CustomerRepository.Add(customer);
				unitOfWork.Commit();
			}

			return ShowMessage("Customer saved");
		}

		[HttpPost]
		public ActionResult Edit(Guid id)
		{
			using (unitOfWork)
			{
				var customer =
					unitOfWork
						.CustomerRepository
						.Single(c => c.Id == id);

				var customerModel = Mapper.Map<Customer, CustomerModel>(customer);
				
				return Render("Edit", customerModel);
			}
		}

		[HttpPost]
		public ActionResult Update(CustomerModel customerModel)
		{
			if (!ModelState.IsValid)
			{
				return Render("Edit", customerModel);
			}

			using (unitOfWork)
			{
				unitOfWork.CustomerRepository.Update(Mapper.Map<CustomerModel, Customer>(customerModel));
				unitOfWork.Commit();

				return ShowMessage("Customer updated");
			}
		}

		[HttpPost]
		public ActionResult Delete(Guid id)
		{
			using (unitOfWork)
			{
				var customer = unitOfWork.CustomerRepository.Find(id);

				unitOfWork.CustomerRepository.Remove(customer);
				unitOfWork.Commit();
			}

			return ShowMessage("Customer deleted");
		}

		private void Initialize()
		{
			Mapper.CreateMap<Customer, CustomerModel>();
			Mapper.CreateMap<CustomerModel, Customer>();
		}
	}
}